package action

import (
	"core/action"
	"core/corestruct"
	"core/myerrors"
	"ht/selfreg"

	htfileservice "ht/service/htfile"
	"reflect"
	"strconv"
)

type DownAction struct {
}

func (p *DownAction) Do(ctx *corestruct.HttpContext) error {

	var c = ctx.Http
	var sid = c.Query("id")
	if "" == sid {
		return myerrors.New("无效的请求")
	}

	var cover = c.Query("cover")
	if cover != "" {
		var act = new(CoverAction)
		return act.Do(ctx)
	}

	var coverShow = c.Query("show")
	if coverShow != "" {
		var act = new(ShowAction)
		return act.Do(ctx)
	}

	var id, _ = strconv.ParseInt(sid, 10, 64)

	var svr = &htfileservice.HtfileService{}
	m, err := svr.Get(id)
	if err != nil {
		return myerrors.NewByErr(err)
	}

	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Disposition", "attachment; filename=\""+m.Name+"\"")
	c.Status(200)
	c.Writer.Write(*m.Data)

	return nil
}

func init() {
	var mact = &DownAction{}
	var maction = action.Action{
		Method: "",

		FullUrl: htfileservice.URLPrev + "/down",
		Name:    "下载" + PAGEName,
		Ename:   "",
		Memo:    "",

		PinType:    "",
		PinIslist:  false,
		PoutType:   "",
		PoutIslist: false,
		PoutIspage: false,

		AuthType: action.AuthType_NONE,

		LogNeed:     false,
		LogPin:      false,
		LogPout:     false,
		LogTemplete: "",

		PrjName: "",

		Value: reflect.ValueOf(mact),
	}
	selfreg.AddAction(&maction)

}
